package renguanyu.app.tools.model;

import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class WordExtract {

	private StringProperty inputFilePath = new SimpleStringProperty();
	private StringProperty outputFileContent = new SimpleStringProperty();
	private String pattern = "^[A-Za-z]+$";

	public final StringProperty inputFilePathProperty() {
		return this.inputFilePath;
	}

	public final String getInputFilePath() {
		return this.inputFilePathProperty().get();
	}

	public final void setInputFilePath(final String inputFilePath) {
		this.inputFilePathProperty().set(inputFilePath);
	}

	public final StringProperty outputFileContentProperty() {
		return this.outputFileContent;
	}

	public final String getOutputFileContent() {
		return this.outputFileContentProperty().get();
	}

	public final void setOutputFileContent(final String outputFileContent) {
		this.outputFileContentProperty().set(outputFileContent);
	}

	public Set<String> getPdfWords(String fileName) {
		Set<String> set = new TreeSet<>();
		PdfReader reader = null;
		try {
			reader = new PdfReader(fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PdfReaderContentParser parser = new PdfReaderContentParser(reader);
		TextExtractionStrategy strategy;
		for (int i = 1; i <= reader.getNumberOfPages(); i++) {
			try {
				strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
				String rows = strategy.getResultantText();
				for (String row : rows.split("\n")) {
					String[] wordArray = row.split(" ");
					for (String word : wordArray) {
						if (Pattern.matches(pattern, word)) {
							set.add(word);
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return set;
	}

	public static void main(String[] args) throws IOException {
		WordExtract pdf = new WordExtract();
		Set<String> words = pdf.getPdfWords("D:\\data\\eclipse\\java\\2024-09\\Tools\\data\\test_pdf.pdf");
		System.out.println(words);
		System.out.println(words.size());
	}

}